package com.kong.controller;


import com.github.abel533.database.IntrospectedTable;
import com.github.abel533.database.SimpleDataSource;
import com.github.abel533.utils.DBMetadataUtils;
import com.kong.consts.DbTypeEnum;
import com.kong.dao.entity.Datasource;
import com.kong.dao.entity.JavaTemplate;
import com.kong.dao.entity.JavaTemplateColumn;
import com.kong.service.DatasourceService;
import com.kong.service.GenerateContext;
import com.kong.service.GenerateContextHolder;
import com.kong.service.JavaTemplateService;
import lombok.extern.slf4j.Slf4j;
import org.seed.mybatis.core.query.Query;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Controller
@Slf4j
public class ViewController {


    @Autowired
    private JavaTemplateService javaTemplateService;
    @Autowired
    private DatasourceService datasourceService;


    /**
     * Step.1 选择数据源
     */
    @GetMapping({"", "/", "home", "index", "home.html", "index.html"})
    public ModelAndView index(ModelMap modelMap) {
        List<Datasource> datasources = datasourceService.list(new Query());
        modelMap.put("datasources", datasources);
        return new ModelAndView("index", modelMap);
    }

    /**
     * Step.2 选择模版组
     */
    @GetMapping("/step2")
    public ModelAndView step2TemplateChoose(String datasourceId, ModelMap modelMap) {
        String token = GenerateContextHolder.putDatasourceId(null, datasourceId);
        modelMap.put("token", token);
        List<JavaTemplate> all = javaTemplateService.list(new Query());
        List<KeyValueVo> keyValueVos = new ArrayList<>();
        Map<String, String> mapTmp = new HashMap<>();
        for (JavaTemplate javaTemplate : all) {
            String key = javaTemplate.getGroupBelong();
            String value = mapTmp.get(key);
            if (StringUtils.hasText(value)) {
                value = value + "," + javaTemplate.getName();
            } else {
                value = javaTemplate.getName();
            }
            mapTmp.put(key, value);
        }
        for (Map.Entry<String, String> entry : mapTmp.entrySet()) {
            KeyValueVo keyValueVo = new KeyValueVo();
            keyValueVo.setKey(entry.getKey());
            keyValueVo.setValue(entry.getValue());
            keyValueVos.add(keyValueVo);
        }
        modelMap.put("groupNames", keyValueVos);
        return new ModelAndView("step2", modelMap);
    }


    /**
     * Step.3 选择表
     */
    @GetMapping("/step3")
    public ModelAndView step3TablesSelect(String token, String groupName, ModelMap modelMap) {
        modelMap.put("token", token);
        Query query = new Query();
        query.eq(JavaTemplateColumn.group_belong, groupName);
        List<JavaTemplate> javaTemplates = javaTemplateService.list(query);
        String templateIds = javaTemplates.stream().map(o -> o.getId()).collect(Collectors.joining(","));
        // 1. 根据GroupName查询全部模版
        GenerateContextHolder.putJavaTemplateId(token, templateIds);
        // 2. 根据选中的datasource查询全部可选择的表
        GenerateContext generateContext = GenerateContextHolder.getByToken(token);
        String datasourceId = generateContext.getDatasourceId();
        Datasource datasource = datasourceService.getById(datasourceId);
        DBMetadataUtils dbUtils = new DBMetadataUtils(new SimpleDataSource(DbTypeEnum.getDialectByName(datasource.getDbType()), datasource.getUrl(), datasource.getUsername(), datasource.getPassword()));
        try {
            List<IntrospectedTable> tables = dbUtils.introspectTables(dbUtils.getDefaultConfig());
            modelMap.put("tables", tables);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        return new ModelAndView("step3", modelMap);

    }

    /**
     * Step3. 的提交选中的表信息
     */
    @PostMapping("/step4")
    @ResponseBody
    public String step4TablesSelect(String token, String tables, ModelMap modelMap) {
        if (tables.startsWith(",")) {
            tables = tables.substring(1);
        }
        GenerateContextHolder.putSelectedTables(token, tables);
        log.info("--> 选中了表: tables");
        return "OK";
    }


}
